package com.ysstech.valuation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.util.BigDecimalUtil;
import com.ysstech.common.util.DateUtil;
import com.ysstech.valuation.entity.SecuritiesDealDetailed;
import com.ysstech.valuation.entity.StockDealDetailed;
import com.ysstech.valuation.mapper.StockDealDetailedMapper;
import com.ysstech.valuation.service.StockDealDetailedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2021-02-22
 */
@Slf4j
@Service
public class StockDealDetailedServiceImpl extends ServiceImpl<StockDealDetailedMapper, StockDealDetailed> implements StockDealDetailedService {

    /**
     * 获取股票交易流水信息，分组汇总的，用来生成股票业务凭证
     *
     * @param accountId
     * @param fdate
     * @return
     * @throws Exception
     */
    public List<StockDealDetailed> queryDatas(String accountId, String fdate) throws Exception {
        QueryWrapper<StockDealDetailed> wrapper = new QueryWrapper<>();
        wrapper.select("STOCKCODE,CURRENCY,MARKET,DEAL_TYPE,INVESTMENT,BUSINESS_TYPE,LISTINGANDCIRCULATION,STOCKTYPE,BUSINESS_SIGN," +
                "SUM(DEAL_AMOUNT) as dealAmount, " +
                "SUM(DEAL_MONEY) as dealMoney ," +
                "SUM(STAMP_FEE) as stampFee ," +
                "SUM(HANDLING_FEE) as handlingFee , " +
                "SUM(TRANSFER_FEE) as transferFee , " +
                "SUM(SECURITIES_MANAGEMENT_FEE) as securitiesManagementFee , " +
                "SUM(COMMISSION_FEE) as commissionFee ," +
                "SUM(RISK_FEE) as riskFee ," +
                "SUM(OTHER_FEE) as otherFee"
        );
        wrapper.eq("ACCOUNT_ID", accountId);
        wrapper.eq("FDATE", DateUtil.strToLocalDate(fdate));
        wrapper.groupBy("BUSINESS_TYPE,CURRENCY,MARKET,INVESTMENT,DEAL_TYPE,BUSINESS_SIGN,STOCKTYPE,LISTINGANDCIRCULATION,STOCKCODE");
        return this.list(wrapper);
    }

    /**
     * 获台ETF账数据当天的细交易数据
     * 关联台账表没有清算完成的
     *
     * @param stockDealDetailed
     * @return
     * @throws Exception
     */
    public Map<String, List<SecuritiesDealDetailed>> queryStockDealDetailed(StockDealDetailed stockDealDetailed) throws Exception {
        Map<String, List<SecuritiesDealDetailed>> map = new LinkedHashMap<>();
        if (null == stockDealDetailed || StringUtils.isBlank(stockDealDetailed.getMarket()) || StringUtils.isBlank(stockDealDetailed.getAccountId())
                || StringUtils.isBlank(stockDealDetailed.getDealSeat()) || null == stockDealDetailed.getFdate()) {
            log.info("没有获取到明细交易数据！");
            return map;
        }
        QueryWrapper<StockDealDetailed> wrapper = new QueryWrapper<>();
        wrapper.eq("MARKET", stockDealDetailed.getMarket());
        wrapper.eq("ACCOUNT_ID", stockDealDetailed.getAccountId());
        wrapper.eq("FDATE", stockDealDetailed.getFdate());
        wrapper.in("DEAL_SEAT", stockDealDetailed.getDealSeat().split(";"));
        wrapper.exists("SELECT SECURITY_CODE FROM etf_account a WHERE CLEAR_CODE = 'N'");
        wrapper.orderByAsc("TRANSACTION_NUMBER");
        List<StockDealDetailed> list = this.list(wrapper);
        String purchase = "";
        for (StockDealDetailed dealDetailed : list) {
            if (null == dealDetailed) {
                continue;
            }
            List<SecuritiesDealDetailed> securitiesDealDetaileds = new ArrayList<>();
            SecuritiesDealDetailed securitiesDealDetailed = new SecuritiesDealDetailed();
            if ("BUY".equals(dealDetailed.getBusinessType())) { //申购
                BigDecimal dealMoney = BigDecimalUtil.add(dealDetailed.getDealMoney(), BigDecimalUtil.add(dealDetailed.getStampFee(), BigDecimalUtil.add(BigDecimalUtil.add(BigDecimalUtil.add(
                        dealDetailed.getHandlingFee(), dealDetailed.getTransferFee()), dealDetailed.getSecuritiesManagementFee()), dealDetailed.getCommissionFee())));
                securitiesDealDetailed.setDealMoney(dealMoney);
                purchase = "SG";
            }
            if ("SELL".equals(dealDetailed.getBusinessType())) { //赎回
                BigDecimal dealMoney = BigDecimalUtil.subtract(dealDetailed.getDealMoney(), BigDecimalUtil.add(dealDetailed.getStampFee(), BigDecimalUtil.add(BigDecimalUtil.add(BigDecimalUtil.add(
                        dealDetailed.getHandlingFee(), dealDetailed.getTransferFee()), dealDetailed.getSecuritiesManagementFee()), dealDetailed.getCommissionFee())));
                securitiesDealDetailed.setDealMoney(dealMoney);
                purchase = "SH";
            }
            if (StringUtils.isBlank(purchase)) {
                continue;
            }
            securitiesDealDetailed.setDealAmount(dealDetailed.getDealAmount());
            String key = dealDetailed.getStockCode() + "\t" + purchase;
            if (map.containsKey(key)) {
                securitiesDealDetaileds = map.get(key);
                securitiesDealDetaileds.add(securitiesDealDetailed);
                map.put(key, securitiesDealDetaileds);
            } else {
                securitiesDealDetaileds.add(securitiesDealDetailed);
                map.put(key, securitiesDealDetaileds);
            }
        }
        return map;
    }
}
